package com.example.milimili;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.example.milimili.bean.NewsInfo;
import com.example.milimili.util.DateUtil;
import com.example.milimili.util.WebChecker;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class NewsFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener,
        SwipeRefreshAndMoreLoadLayout.OnLoadMoreListener{
    private ListView newsList = null;
    private ImageView myImage = null;
    private TextView newsText,chubanText,dateText;
    public String json;
    public String category;
    private String path;
    private int sizecount=50;
    View view;
    List<HashMap<String, Object>> jsonMap = new ArrayList<HashMap<String, Object>>();
    private SwipeRefreshAndMoreLoadLayout mRefreshLayout;
    private List<Boolean> videoCheck=new ArrayList<>();
    private MyAdapter myAdapter=new MyAdapter();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//        return super.onCreateView(inflater, container, savedInstanceState);
        view = inflater.inflate(R.layout.newslistlayout, container, false);
        newsList=view.findViewById(R.id.listview);
        mRefreshLayout = (SwipeRefreshAndMoreLoadLayout) view.findViewById(R.id.refresh);
        mRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);
        mRefreshLayout.setAdapte(newsList, myAdapter);
        if(WebChecker.isConnectIsNormal(getContext()))
        {
            Log.e("web:","有网络");
            Thread webThread=new Thread(new Runnable() {
                @Override
                public void run() {
                    getWeb();
                }
            });
            path=MainActivity.FIRSTPART+ DateUtil.getNowDateTime()+MainActivity.SECONDPART+MainActivity.THIRDPART+category;
            webThread.start();
            try {
                webThread.join();
//            Log.e("json",json);
                getJson();
//                MyAdapter myAdapter=new MyAdapter();
                newsList.setAdapter(myAdapter);
                newsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        if(videoCheck.get(i))
                        {
                            Intent intent=new Intent(view.getContext(),VedioNewsActivity.class);
                            final SerializableMap myMap=new SerializableMap();
                            myMap.setMap(jsonMap.get(i));//将map数据添加到封装的myMap中
                            myMap.setPosition(i);
                            myMap.setPath(path);
                            Bundle bundle=new Bundle();
                            bundle.putSerializable("map", myMap);
                            intent.putExtras(bundle);
                            MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(getContext());
                            NewsInfo newsInfo = new NewsInfo();
                            newsInfo.setTitle(jsonMap.get(i).get("title").toString());
                            newsInfo.setImage(jsonMap.get(i).get("image").toString());
                            newsInfo.setPath(path);
                            newsInfo.setPosition(i);
                            newsInfo.setContent(jsonMap.get(i).get("content").toString());
                            long rowId = mySQLiteOpenHelper.insertData(2,newsInfo);
                            Log.e("gray","变灰");
                            myAdapter.notifyDataSetChanged();
                            startActivity(intent);
                        }
                        else {
                            NewsActivity.flag=true;
//                Log.e("点击：",jsonMap.get(i).get("title").toString());
                            Intent intent=new Intent(view.getContext(),NewsActivity.class);
                            final SerializableMap myMap=new SerializableMap();
                            myMap.setMap(jsonMap.get(i));//将map数据添加到封装的myMap中
                            myMap.setPosition(i);
                            myMap.setPath(path);
                            Bundle bundle=new Bundle();
                            bundle.putSerializable("map", myMap);
                            intent.putExtras(bundle);
                            MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(getContext());
                            NewsInfo newsInfo = new NewsInfo();
                            newsInfo.setTitle(jsonMap.get(i).get("title").toString());
                            newsInfo.setImage(jsonMap.get(i).get("image").toString());
                            newsInfo.setPath(path);
                            newsInfo.setPosition(i);
                            newsInfo.setContent(jsonMap.get(i).get("content").toString());
                            long rowId = mySQLiteOpenHelper.insertData(2,newsInfo);
//                            Log.e("gray","变灰");
                            myAdapter.notifyDataSetChanged();
                            startActivity(intent);
                        }
                    }
                });
//                mRefreshLayout = (SwipeRefreshAndMoreLoadLayout) view.findViewById(R.id.refresh);
//                mRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
//                        android.R.color.holo_green_light,
//                        android.R.color.holo_orange_light,
//                        android.R.color.holo_red_light);
//                mRefreshLayout.setOnRefreshListener(this);
//                mRefreshLayout.setOnLoadMoreListener(this);
//                mRefreshLayout.setAdapte(newsList, myAdapter);
//            final SwipeRefreshLayout swip_refresh_layout=view.findViewById(R.id.swipeLayout);
//            swip_refresh_layout.setColorSchemeResources(R.color.themeRed);
////            swip_refresh_layout.setProgressBackgroundColorSchemeColor(R.color.themeRed);
//            swip_refresh_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//                @Override
//                public void onRefresh() {
//                    new Handler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            swip_refresh_layout.setRefreshing(false);
//                        }
//                    },1000);
//                }
//            });
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        else
        {
            ;
        }
        return view;
    }

//    Thread webThread = new Thread(new Runnable() {
//        @Override
//        public void run() {
//            getWeb();
//        }
//    });

    private void getWeb() {
        try {
            json = HtmlService.getHtml(path);
//            System.out.println(json.length());
//            Log.e(TAG, "html : " + json);
//            System.out.println(html);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getJson() {
        try {
//            Log.e(TAG,json);
            JSONObject rootObject=new JSONObject(json);
            JSONArray dataArray=rootObject.getJSONArray("data");
            for(int i=0;i<dataArray.length();i++)
            {
                JSONObject newsObject = dataArray.getJSONObject(i);
                String imageAll=newsObject.getString("image");
                String imageTmp=imageAll.substring(1,imageAll.length()-1);
//                String[] imageArray=imageTmp.split(", ");
                String video= newsObject.getString("video");
                String title= newsObject.getString("title");
                String content=newsObject.getString("content");
                String organizations= newsObject.getString("organizations");
                String publisher=newsObject.getString("publisher");
                String time=newsObject.getString("publishTime");
//                Log.e(TAG,title);
                HashMap<String, Object> map = new HashMap<>();
                map.put("image",imageTmp);
                map.put("video", video);
                map.put("title", title);
                map.put("content",content);
                map.put("organization", organizations);
                map.put("publisher",publisher);
                map.put("publishTime",time);
                jsonMap.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                if(WebChecker.isConnectIsNormal(getContext()))
                {
//                    mRefreshLayout = (SwipeRefreshAndMoreLoadLayout) view.findViewById(R.id.refresh);
//                    mRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
//                            android.R.color.holo_green_light,
//                            android.R.color.holo_orange_light,
//                            android.R.color.holo_red_light);
//                    mRefreshLayout.setOnRefreshListener(NewsFragment.this);
//                    mRefreshLayout.setOnLoadMoreListener(NewsFragment.this);
//                    mRefreshLayout.setAdapte(newsList, myAdapter);
                    Thread webThread=new Thread(new Runnable() {
                        @Override
                        public void run() {
                            getWeb();
                        }
                    });
                    path=MainActivity.FIRSTPART+ DateUtil.getNowDateTime()+MainActivity.SECONDPART+MainActivity.THIRDPART+category;
                    webThread.start();
                    try {
                        webThread.join();
                        getJson();
//                MyAdapter myAdapter=new MyAdapter();
                        newsList.setAdapter(myAdapter);
                        newsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                if(videoCheck.get(i))
                                {
                                    Intent intent=new Intent(view.getContext(),VedioNewsActivity.class);
                                    final SerializableMap myMap=new SerializableMap();
                                    myMap.setMap(jsonMap.get(i));//将map数据添加到封装的myMap中
                                    myMap.setPosition(i);
                                    myMap.setPath(path);
                                    Bundle bundle=new Bundle();
                                    bundle.putSerializable("map", myMap);
                                    intent.putExtras(bundle);
                                    MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(getContext());
                                    NewsInfo newsInfo = new NewsInfo();
                                    newsInfo.setTitle(jsonMap.get(i).get("title").toString());
                                    newsInfo.setImage(jsonMap.get(i).get("image").toString());
                                    newsInfo.setPath(path);
                                    newsInfo.setPosition(i);
                                    newsInfo.setContent(jsonMap.get(i).get("content").toString());
                                    long rowId = mySQLiteOpenHelper.insertData(2,newsInfo);
//                                    Log.e("gray","变灰");
                                    myAdapter.notifyDataSetChanged();
                                    startActivity(intent);
                                }
                                else {
                                    NewsActivity.flag=true;
//                Log.e("点击：",jsonMap.get(i).get("title").toString());
                                    Intent intent=new Intent(view.getContext(),NewsActivity.class);
                                    final SerializableMap myMap=new SerializableMap();
                                    myMap.setMap(jsonMap.get(i));//将map数据添加到封装的myMap中
                                    myMap.setPosition(i);
                                    myMap.setPath(path);
                                    Bundle bundle=new Bundle();
                                    bundle.putSerializable("map", myMap);
                                    intent.putExtras(bundle);
                                    MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(getContext());
                                    NewsInfo newsInfo = new NewsInfo();
                                    newsInfo.setTitle(jsonMap.get(i).get("title").toString());
                                    newsInfo.setImage(jsonMap.get(i).get("image").toString());
                                    newsInfo.setPath(path);
                                    newsInfo.setPosition(i);
                                    newsInfo.setContent(jsonMap.get(i).get("content").toString());
                                    long rowId = mySQLiteOpenHelper.insertData(2,newsInfo);
//                                    Log.e("gray","变灰");
                                    myAdapter.notifyDataSetChanged();
                                    startActivity(intent);
                                }
                            }
                        });
                        myAdapter.notifyDataSetChanged();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                else
                {
                    ;
                }
                mRefreshLayout.setRefreshing(false);
            }
        }, 5000);
    }

    @Override
    public void onLoadMore() {
        mRefreshLayout.setLoadingContext("正在加载");
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                if(WebChecker.isConnectIsNormal(getContext()))
                {
                    sizecount=sizecount+50;
                    path=MainActivity.ONEPART+sizecount+MainActivity.TWOPART+DateUtil.getNowDateTime()+MainActivity.SECONDPART+MainActivity.THIRDPART+category;
                    Thread webThread=new Thread(new Runnable() {
                        @Override
                        public void run() {
                            getWeb();
                        }
                    });
                    webThread.start();
                    try {
                        webThread.join();
                        jsonMap.clear();
                        getJson();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                else
                {
                    ;
                }
                mRefreshLayout.setLoading(false);
            }
        }, 5000);
    }

//    private void initListener() {
//        newsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
////                Log.e("点击：",jsonMap.get(i).get("title").toString());
//                Intent intent=new Intent(MainActivity.this,NewsActivity.class);
//                final SerializableMap myMap=new SerializableMap();
//                myMap.setMap(jsonMap.get(i));//将map数据添加到封装的myMap中
//                Bundle bundle=new Bundle();
//                bundle.putSerializable("map", myMap);
//                intent.putExtras(bundle);
//                startActivity(intent);
//            }
//        });
//    }

//    private void initView() {
//        newsList=view.findViewById(R.id.listview);
//        MyAdapter myAdapter=new MyAdapter();
//        newsList.setAdapter(myAdapter);
//    }

    private class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() { return jsonMap.size(); }

        @Override
        public Object getItem(int i) {
            return jsonMap.get(i).get("title");
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View itemView=View.inflate(getContext(),R.layout.itemlayout,null);
            newsText=itemView.findViewById(R.id.name);
            myImage=itemView.findViewById(R.id.picture);
            newsText.setText(jsonMap.get(i).get("title").toString());
            chubanText=itemView.findViewById(R.id.chuban);
            if(jsonMap.get(i).get("publisher")!=null)
            {
                chubanText.setText(jsonMap.get(i).get("publisher").toString());
            }
            dateText=itemView.findViewById(R.id.date);
            if(jsonMap.get(i).get("publishTime")!=null)
            {
                dateText.setText(jsonMap.get(i).get("publishTime").toString());
            }
//            if(jsonMap.get(i).get("video").toString().length()!=0)
            if(jsonMap.get(i).get("video").toString()  .length()!=0||i==0)
            {
                videoCheck.add(true);
                Log.e("视频：","有一个视频不为空"+"  "+jsonMap.get(i).get("title").toString());
            }
            else
            {
                videoCheck.add(false);
            }
            MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(getContext());
            if(mySQLiteOpenHelper.checkFromDbByTitle(2,jsonMap.get(i).get("title").toString()))
            {
                ;
            }
            else
            {
                newsText.setTextColor(Color.parseColor("#7D7D7D"));
                chubanText.setTextColor(Color.parseColor("#7D7D7D"));
                dateText.setTextColor(Color.parseColor("#7D7D7D"));
            }
            String imageAll=jsonMap.get(i).get("image").toString();
            String[] imageArray=imageAll.split(", ");
            if(imageArray.length!=0)
            {
//                Log.e("imagecheck:",imageArray[0]);
                Glide.with(getContext()).load(imageArray[0]).into(myImage);
            }
            return itemView;
        }


    }

}

